package net.maku.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import net.maku.bean.model.MyException;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
public class JsonUtils {
    private static final ObjectMapper JSON = new ObjectMapper();
    static {
        JSON.setSerializationInclusion(Include.NON_NULL);
        JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
    }

    public static String toJson(Object obj) {
        try {
            return JSON.writeValueAsString(obj);
        } catch ( Exception e ) {
            e.printStackTrace();
            throw new MyException("json转换失败：" + e.getMessage() );
        }
    }
    
    public static <T> T fromJson( String json,  Class<T> destType ) {
        try {
        	return JSON.readValue(json, destType);
        } catch ( Exception e ) {
            e.printStackTrace();
            throw new MyException("json解析失败：" + e.getMessage() );
        }
    }
    
    
    public static JsonNode fromJson( String json ) {
        try {
        	return JSON.readTree(json); 
        } catch ( Exception e ) {
            e.printStackTrace();
            throw new MyException("json解析失败：" + e.getMessage() );
        }
    }
    
    public static String getStr( String json, String key ) {
    	try {
			return JSON.readTree(json).get(key).textValue();
    	} catch ( Exception e ) {
            e.printStackTrace();
            throw new MyException("json解析失败：" + e.getMessage() );
        }
    }
    
    public static String getStr( JsonNode node, String key ) {
    	return node.get(key).textValue();
    }
}

